var currentpage = 1,totlepage = 1,i,alarmvalueImg;//分页的当前页和总的页数 电量图标
//自定义报表数据
var tableData = [],schoolDataList = [],schoolDataAll = [];
//报表对应的数据
var otherData = {pageLeft:0,pageRight:0};
var Page = React.createClass({
    setPage: function (e) {
        setPage($(e.target).html());
        this.props.onPageClick(1);
    },
    showPage: function () {
        showPage();
    },
    render: function () {
        {
            var items = [],
                svar = this;
            if(totlepage == 0 ){
                items.push({num:1,checked:true})
            }else if(totlepage < 6){
                for(i = 1;i <= totlepage ;i++) {
                    if (i == currentpage) {
                        items.push({num:i,checked:true})
                    } else {
                        items.push({num:i,checked:false})
                    }
                }
            }else if(currentpage >= (totlepage-2)) {//点在左边
                items.push({num:1,checked:false});
                items.push({num:'···',checked:false});
                for(i = totlepage-2;i <= totlepage ;i++){
                    if(i == currentpage){
                        items.push({num:i,checked:true})
                    }else{
                        items.push({num:i,checked:false})
                    }
                }
            }else if(currentpage <= 3){
                for(i = 1;i <= 3 ;i++) {
                    if (i == currentpage) {
                        items.push({num:i,checked:true})
                    } else {
                        items.push({num:i,checked:false})
                    }
                }
                items.push({num:'···',checked:false});
                items.push({num:totlepage,checked:false})
            }else {//点在两边
                items.push({num:1,checked:false});
                items.push({num:'···',checked:false});
                items.push({num:currentpage-1,checked:false});
                items.push({num:currentpage,checked:true});
                items.push({num:currentpage+1,checked:false});
                items.push({num:'···',checked:false});
                items.push({num:totlepage,checked:false})
            }
        }
        return (
            <div className="tableInfo-page">
                <div className="page-number">每页<span className="page-number-list" onClick={this.showPage}>{pagecount}</span>条</div>
                <div className="page-list" style={{top:pageListTop+"px"}}>
                    <ul>
                        {
                            pageList.map(function (item) {
                                return (<li onClick={svar.setPage}>{item}</li>)
                            })
                        }
                    </ul>
                </div>
                <div className="page-limit">
                    <ol className="page-limit-ol">
                        <li className="page-limit-img" name="-1" onClick={otherData.pageLeft == 0?'':svar.props.onPageClick.bind(svar,-1)} ><span className={otherData.pageLeft == 0?'page-limit-left-no':'page-limit-left-yes'}/></li>
                        {
                            items.map(function (item) {
                                return (<li onClick={isNaN(item.num)?'':svar.props.onPageClick.bind(svar,item.num)}  className={item.checked == true?'page-limit-num page-limit-checked':'page-limit-num'} name={item.num}>{item.num}</li>)
                            })
                        }
                        <li className="page-limit-img" name="-2" onClick={otherData.pageRight == 0?'':svar.props.onPageClick.bind(svar,-2)} ><span className={otherData.pageRight == 0?'page-limit-right-no':'page-limit-right-yes'}/></li>
                    </ol>
                </div>
            </div>
        );
    },
});
//表单组件
var Table = React.createClass({
    render: function () {
        return (
            <tr>
                <td >{parseInt(this.props.listNumber)+1}</td>
                <td >{this.props.mdtid}</td>
                <td >{this.props.simid}</td>
                <td>{this.props.status == '0'?"在线":"离线"}</td>
                <td>{this.props.alarmtype==20?<img src={"../img/icon/"+this.props.alarmvalueImg} title={this.props.alarmvalue} />:""}</td>
                <td style={{display:"none"}}>{this.props.recvtime}</td>
                <td >{this.props.maxrecvtime}</td>
                <td>{this.props.maxrecvtime == "未知"?'':<div className="trButton table-click" onClick={this.props.onClickTrack}>追踪</div>}</td>
            </tr>
        );
    }
});
//父组件
var Main = React.createClass({
    //组件初始状态
    getInitialState: function () {
        return {
            otherData:this.props.otherData,
            tableData:this.props.tableData,
            schoolDataList:this.props.schoolDataList,
            schoolDataAll:this.props.schoolDataAll,
        }
    },
    componentDidMount: function () {
        //使用ajax取出数据然后组装数据列表
        var svar = this;
        suixun.ajax(serverUrl+'/monitorManager/queryMonitorList.json?param={pagenumber:1,pagecount:'+pagecount+'}','',"get",function(data){
            suixun.hideLoding();//隐藏加载中
            if(data.code == 200){
                for(var i=0;i<data.info.queryresult.length;i++){
                    var obj=data.info.queryresult[i];
                    var alarmvalue = obj.alarmvalue,alarmtype = obj.alarmtype;
                    if(alarmtype == 20){
                        if(alarmvalue > "95" ){
                            alarmvalueImg = "electricity-four.png";
                        }else if(alarmvalue > "80" ){
                            alarmvalueImg = "electricity-three.png";
                        }else if(alarmvalue > "50" ){
                            alarmvalueImg = "electricity-two.png";
                        }else if(alarmvalue > "20" ){
                            alarmvalueImg = "electricity-one.png";
                        }else{
                            alarmvalueImg = "electricity-zero.png";
                        }
                    }else{
                        alarmvalueImg = "";
                    }
                    tableData[i] = {
                        keyid:i,
                        objectid:obj.objectid,
                        mdtid:obj.mdtid,
                        simid:obj.simid,
                        alarmvalue:alarmvalue,
                        alarmtype:obj.alarmtype,
                        alarmvalueImg:alarmvalueImg,
                        recvtime:obj.recvtime,
                        maxrecvtime:obj.maxrecvtime,
                        status:obj.status
                    };
                }
                var pageRight = 0;
                if(data.info.totlepage > 1){
                    pageRight = 1
                }
                otherData = {pageLeft:0,pageRight:pageRight};
                currentpage = 1;totlepage = data.info.totlepage;//初始化的时候赋值：分页的当前页和总的页数
                svar.setState({tableData:tableData,otherData:otherData});
                svar.selectSchoolData();//查询学校列表
            }
        });
        //绑定回车时间
        $(document).keypress(function(e) {
            var eCode = e.keyCode ? e.keyCode : e.which ? e.which : e.charCode;
            if (eCode == 13){
                if($(".enterEvent").is(":focus")){
                    svar.onClickQuery();
                }
            }
        });
    },
    //查询学校数据
    selectSchoolData: function () {
        suixun.showLoding();//显示加载中
        var svar = this;
        suixun.ajax(serverUrl+'/schoolManage/querySchool.json','',"get",function(data){
            suixun.hideLoding();//隐藏加载中
            if(data.code == 200 ){
                for(var i=0;i<data.info.length;i++){
                    var obj=data.info[i];
                    schoolDataList[i] = {key:i,id:obj.id,schoolname:obj.schoolname};
                }
                schoolDataAll = schoolDataList;
                svar.setState({schoolDataList:schoolDataList,schoolDataAll:schoolDataAll});
            }else{
                svar.setState({schoolDataList:schoolDataList,schoolDataAll:schoolDataAll});
            }
        });
    },
    /**
     * 点击搜索学校下拉列表
     */
    onClickQuerySchoolList: function (e) {
        $(".queryVal").val($(e.target).html());
        this.onClickQuery();
    },
    /**
     * 点击搜索
     */
    onClickQuery: function () {
        var svar = this,queryType = $(".school-or-table").html(),queryKey = "schoolname",inputValue = $(".queryVal").val();
        if(queryType == "设备IMEI号"){
            queryKey = "mdtid";
            if(!/^[1-9]\d*$/.test(inputValue) && inputValue != ""){
                suixun.alert("设备IMEI号格式不对！",function (data) {
                    if(data){
                        $(".queryVal").val("")
                    }
                });
                return;
            }
        }else if(queryType == "设备手机号"){
            queryKey = "simid";
            if(!/^[1-9]\d*$/.test(inputValue) && inputValue != ""){
                suixun.alert("设备手机号格式不对！",function (data) {
                    if(data){
                        $(".queryVal").val("")
                    }
                });
                return;
            }
        }
        suixun.showLoding();//显示加载中
        var param="param={";
        param = getJsonDataNotEmpty(param,""+queryKey+"",'"'+inputValue+'"');
        param = getJsonDataNotEmpty(param,"pagenumber","1");
        param = getJsonDataNotEmpty(param,"pagecount",pagecount+'');
        param += "}";
        suixun.ajax(serverUrl+'/monitorManager/queryMonitorList.json',param,"get",function(data){
            tableData = [];
            if(data.code == 200 && data.info != null){
                for(var i=0;i<data.info.queryresult.length;i++){
                    var obj=data.info.queryresult[i];
                    var alarmvalue = obj.alarmvalue,alarmtype = obj.alarmtype;
                    if(alarmtype == "20"){
                        if(alarmvalue > "95" ){
                            alarmvalueImg = "electricity-four.png";
                        }else if(alarmvalue > "80" ){
                            alarmvalueImg = "electricity-three.png";
                        }else if(alarmvalue > "50" ){
                            alarmvalueImg = "electricity-two.png";
                        }else if(alarmvalue > "20" ){
                            alarmvalueImg = "electricity-one.png";
                        }else{
                            alarmvalueImg = "electricity-zero.png";
                        }
                    }
                    tableData[i] = {
                        keyid:i,
                        objectid:obj.objectid,
                        mdtid:obj.mdtid,
                        simid:obj.simid,
                        alarmvalue:alarmvalue,
                        alarmtype:alarmtype,
                        alarmvalueImg:alarmvalueImg,
                        recvtime:obj.recvtime,
                        maxrecvtime:obj.maxrecvtime,
                        status:obj.status
                    };
                }
                var pageRight = 0;
                if(data.info.totlepage > 1){
                    pageRight = 1
                }
                otherData = {pageLeft:0,pageRight:pageRight};
                currentpage = 1;totlepage = data.info.totlepage;//初始化的时候赋值：分页的当前页和总的页数
                svar.setState({tableData:tableData,otherData:otherData});
                suixun.hideLoding();//隐藏加载中
            }else{
                suixun.hideLoding();//隐藏加载中
                otherData = {pageLeft:0,pageRight:0};
                currentpage = 1;totlepage = 1;//初始化的时候赋值：分页的当前页和总的页数
                svar.setState({tableData:tableData,otherData:otherData});
            }
        });
    },
    //分页
    onPageClick: function (num) {
        //分页-调用ajac然后把数据查询出来:获取name的值
        //计算currentpage
        suixun.showLoding();//显示加载中
        var onPageLeft = 0,onPageRight = 1,svar = this;
        if(num > 0){
            currentpage = num;
        }else if(num == -1 && currentpage > 1){
            currentpage --;
        }else if(num == -2  && currentpage < totlepage){
            currentpage ++;
        }
        //修改左右的按钮
        if((currentpage == totlepage && totlepage == 1)|| totlepage == 0){
            onPageLeft = 0;
            onPageRight = 0;
        }else if(currentpage == totlepage && totlepage > 1){
            onPageLeft = 1;
            onPageRight = 0;
        }else if(1 < currentpage && currentpage < totlepage){
            onPageLeft = 1;
            onPageRight = 1;
        }

        var queryType = $(".school-or-table").html(),queryKey = "schoolname";
        if(queryType == "设备IMEI号"){
            queryKey = "mdtid";
        }else if(queryType == "设备手机号"){
            queryKey = "simid";
        }
        var param="param={";
        param = getJsonDataNotEmpty(param,""+queryKey+"",$(".queryVal").val());
        param = getJsonDataNotEmpty(param,"pagenumber",""+currentpage+"");
        param = getJsonDataNotEmpty(param,"pagecount",pagecount+'');
        param += "}";
        suixun.ajax(serverUrl+'/monitorManager/queryMonitorList.json',param,"get",function(data){
            tableData = [];
            if(data.code == 200){
                for(var i=0;i<data.info.queryresult.length;i++){
                    var obj=data.info.queryresult[i];
                    var alarmvalue = obj.alarmvalue,alarmtype = obj.alarmtype;
                    if(alarmtype == "20"){
                        if(alarmvalue > "95" ){
                            alarmvalueImg = "electricity-four.png";
                        }else if(alarmvalue > "80" ){
                            alarmvalueImg = "electricity-three.png";
                        }else if(alarmvalue > "50" ){
                            alarmvalueImg = "electricity-two.png";
                        }else if(alarmvalue > "20" ){
                            alarmvalueImg = "electricity-one.png";
                        }else{
                            alarmvalueImg = "electricity-zero.png";
                        }
                    }
                    tableData[i] = {
                        keyid:i,
                        objectid:obj.objectid,
                        mdtid:obj.mdtid,
                        simid:obj.simid,
                        alarmvalue:alarmvalue,
                        alarmtype:alarmtype,
                        alarmvalueImg:alarmvalueImg,
                        recvtime:obj.recvtime,
                        maxrecvtime:obj.maxrecvtime,
                        status:obj.status
                    };
                }
                if(data.info.totlepage > 1 && data.info.totlepage > currentpage){
                    onPageRight = 1
                }else{
                    onPageRight = 0;
                }
                otherData = {pageLeft:onPageLeft,pageRight:onPageRight};
                totlepage = data.info.totlepage;//初始化的时候赋值：分页的当前页和总的页数
                svar.setState({tableData:tableData,otherData:otherData});
                suixun.hideLoding();//隐藏加载中
            }else{
                otherData = {pageLeft:0,pageRight:0};
                currentpage = 1;totlepage = 1;//初始化的时候赋值：分页的当前页和总的页数
                svar.setState({tableData:tableData,otherData:otherData});
                suixun.hideLoding();//隐藏加载中
            }
        });
    },
    //点击追踪
    onClickTrack: function (info) {
        var param="param={";
        param = getJsonDataNotEmpty(param,"objectid",""+info[0]+"");
        param = getJsonDataNotEmpty(param,"maxrecvtime","'"+info[1]+"'");
        param += "}";
        suixun.ajax(serverUrl+'/monitorManager/queryMapMonitorsByFollow.json',param,"get",function(data){
            if(data.code == 200){
                localStorage.followPointInfo = info[0]+"*"+info[1];
                window.location.href = "queryMonitorList.html";
            }else{
                suixun.alert("追踪失败!");
            }
        });
    },
    //点击列表
    onClickMenu: function () {
        window.location.href = "queryMonitorList.html";
    },
    //改变弹出层学校输入框
    onChangSchoolInput: function (e) {
        if($(".school-or-table").html() == "设备IMEI号" || $(".school-or-table").html() == "设备手机号"){
            return;
        }
        var val = $(e.target).val();
        if(val != ""){
            this.schoolArray(val,$(e.target).attr("data-list"));
        }else{
            $("."+$(e.target).attr("data-list")+"").hide();
        }
    },
    //排序
    schoolArray: function (val,cls) {
        schoolDataList = [];
        for(var i = 0;i < schoolDataAll.length;i++){
            if((schoolDataAll[i].schoolname).indexOf(val) >= 0){
                schoolDataList.push({schoolname:schoolDataAll[i].schoolname});
            }
        }
        if(schoolDataList.length == 0){
            $("."+cls+"").hide();
        }else{
            $("."+cls+"").show();
            this.setState({schoolDataList:schoolDataList});
        }
    },
    //点击学校输入框
    onClickSchool: function (e) {
        if($(".school-or-table").html() == "设备IMEI号" || $(".school-or-table").html() == "设备手机号"){
            return;
        }
        var val = $(e.target).val();
        this.schoolArray(val,$(e.target).attr("data-list"));
    },
    render: function () {
        {
            var svar = this;
            var onClickArray = [this.onClickTrack];
            var Tabels = this.state.tableData.map(function (data,index) {
                return (
                    <Table key={data.key} listNumber={index} onClickTrack={onClickArray[0].bind(svar,[data.objectid,data.maxrecvtime])} alarmtype={data.alarmtype} status={data.status} alarmvalueImg={data.alarmvalueImg} objectid={data.objectid} mdtid={data.mdtid} simid={data.simid} alarmvalue={data.alarmvalue} recvtime={data.recvtime} maxrecvtime={data.maxrecvtime}  />
                )
            });
        }
        return (
            <div className="tableManage-body">
                <header>
                    <div className="header-menu">
                        <ul>
                            <li onClick={this.onClickMenu}>地图监控</li>
                            <li className="select">列表监控</li>
                        </ul>
                        <div className="header-right">
                            <div className="header-right-select droup-select">
                                <div className="school-or-table">学校</div>
                                <span className="lower-right-corner"/>
                                <div className="drop-down" >
                                    <span className="select-value school-name" >学校</span>
                                    <span className="select-value school-name" >设备IMEI号</span>
                                    <span className="select-value student-name" >设备手机号</span>
                                </div>
                            </div>
                            <div className="header-right-query">
                                <div className="header-right-query-input">
                                    <input className="queryVal enterEvent" type="text" onChange={this.onChangSchoolInput} onClick={this.onClickSchool}  data-list="querySchoolTable" maxLength="50" id="searchName" name="searchName"  placeholder="请输入学校关键字"/>
                                </div>
                                <div className="header-right-query-img-user" onClick={this.onClickQuery}></div>
                                <div className="schoolList querySchoolTable" data-inputId="searchName">
                                    {
                                        schoolDataList.map(function (data) {
                                            return (
                                                <span className="schoolList-value" onClick={svar.onClickQuerySchoolList}>{data.schoolname}</span>
                                            )
                                        })
                                    }
                                </div>
                            </div>
                        </div>
                    </div>
                </header>
                <div className="tableInfo ">
                    <div className="studentsInfo-data tableInfo-data">
                        <div className="studentsInfo-data-table tableInfo-data-table" >
                            <table className="head-body head-body">
                                <thead>
                                    <th>序号</th>
                                    <th>设备IMEI</th>
                                    <th>设备手机号</th>
                                    <th>在线状态</th>
                                    <th>电量信息</th>
                                    <th style={{display:"none"}}>在线时间</th>
                                    <th>最后一次上报时间</th>
                                    <th>设备控制</th>
                                    </thead>
                                <tbody>
                                    {this.state.tableData==""?'':Tabels}
                                </tbody>
                            </table>
                            {this.state.tableData==""?<div className="tableNoData">{tableNoDataCount}</div>:''}
                        </div>
                    </div>
                    <Page otherData={this.state.otherData} onPageClick={this.onPageClick} />
                </div>
                <footer id="copyright">
                    <span><img src="../img/icon/copyright.png"/>{copyright}</span>
                </footer>
            </div>
        )
    }
});
ReactDOM.render(
    <Main  otherData={otherData} tableData={tableData} schoolDataList={schoolDataList} schoolDataAll={schoolDataAll} />,
    document.getElementById('tableManage')
);
//点击下拉框
$(".header-right-select").click(function () {
    var dropDown = $(this).find('.drop-down');
    if(dropDown.is(":hidden")){
        dropDown.slideDown();
    }else{
        dropDown.slideUp();
    }
});
//选择学校、imei、手机号
$('.drop-down > span').click(function() {
    $(".queryVal").attr("placeholder","请输入"+$(this).html()+"关键字");
    var value = $(this).html();
    if(value == "学校" && $(".school-or-table").html() != "学校"){
        $("#searchName").val("");
    }else if(value == "设备IMEI号" && $(".school-or-table").html() != "设备IMEI号"){
        $("#searchName").val("");
    }else if(value == "设备手机号" && $(".school-or-table").html() != "设备手机号"){
        $("#searchName").val("");
    }
    $(".school-or-table").html($(this).html());
    $('.drop-down').slideUp();
});
//学校下拉列表
$("*").bind("click",function(e){
    var target = $(e.target);
    if(target.closest(".schoolList-value").length == 1){
        $("#"+$(target.parent()).attr("data-inputId")+"").val(target.html());
        $(".schoolList").hide();
    }else{
        $(".schoolList").hide();
    }
});